<?php
session_start();
?>
<html>
<?php
    
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minates ago
    session_unset();     // unset $_SESSION variable for the runtime 
    session_destroy();   // destroy session data in storage
    
    $host  = $_SERVER['HTTP_HOST'];
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $extra = 'index.php';
    header("Location: http://$host$uri/$extra?expire=true");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>     
    <head> 
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title>Botany Dichotomous Key Conversion System</title>
            <link rel="stylesheet" type="text/css" href="css/default.css" />
            <link rel="stylesheet" type="text/css" href="css/stepsMenu.css" />
            
            <script type="text/javascript" src="webforms2/webforms2-p.js"></script> 
            
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
          
            <script src="http://html5form.googlecode.com/svn/trunk/jquery.html5form-1.5-min.js"></script>
    
            <script>
                $(document).ready(function(){
                    $('#characteristics').html5form();    
                    messages : 'de',
                    responseDiv : '#req';
                });
            </script>
    
    </head>
    
    <body>
            <?php 
            $uploaddir= $_POST["output"];
            $inputFile = $uploaddir."keyconversion.xml";
            $xml = simplexml_load_file($inputFile);
            $sxe = new SimpleXMLElement($xml->asXML());
            //This is the directory where images will be saved 
            $target = $uploaddir; 
            //$target = $target . basename( $_FILES['photo']['name']);
       
            //Upload Node Images
            $Nodecount = count($xml->nodes->Node);
            //echo "Node count = ".$Nodecount."<br />";
            for($i = 0; $i < $Nodecount; $i++){
                if($sxe->nodes->Node[$i]->isLeafNode == "no"){
                    //echo "Node id: ".$xml->nodes->Node[$i]->nodeID."<br>";
                    //For Left child image
                    $leftImagecount = 0;
                    $leftChildButtonId = "node".$xml->nodes->Node[$i]->leftChildID."image";
                    $decisionNode = $sxe->nodes->Node[$i];
                    $nodeElementNameL = "left_image";
                    
                    /**************************/
                    $existLeftImage = count($decisionNode->left_image);
                    if($existLeftImage > 0){
                        unset($decisionNode->left_image);
                    }
                    /**************************/                    
                    
                    foreach($_FILES["$leftChildButtonId"] as $key)
                    {
                        
                        $nodeLeftImgName = "node" . $xml->nodes->Node[$i]->leftChildID. $leftImagecount . ".png";

                        if(!empty($_FILES["$leftChildButtonId"]["tmp_name"][$leftImagecount]) )
                        {
                            //echo "1 " . $leftImagecount . $nodeLeftImgName . $leftChildButtonId. "<br>";

                            $splitName = explode(".", $_FILES["$leftChildButtonId"]["name"][$leftImagecount]); // Split file name into an array using the dot
                            $imgFileExt = end($splitName); // Now target the last array element to get the file extensio
                            if (strtolower($imgFileExt) != "png") {

                               imageConversion($leftChildButtonId,$nodeLeftImgName,$imgFileExt, $leftImagecount);
                               $decisionNode->addChild("left_image", $nodeLeftImgName);
                            }

                            else{
                                 move_uploaded_file($_FILES["$leftChildButtonId"]["tmp_name"][$leftImagecount],$uploaddir.$nodeLeftImgName);
                                 $decisionNode->addChild("left_image", $nodeLeftImgName); 
                            }
                        }
                        /*else {
                            //echo "no left child image <br>";
                         $decisionNode->addChild("left_image"); 
                        }*/
                        $leftImagecount++;
                    }
                    
                    //For Right Child image
                    $rightImagecount = 0;
                    $rightChildButtonId = "node".$xml->nodes->Node[$i]->rightChildID."image";
                    //echo "rightChildID = ".$rightChildButtonId."<br>";
                    $decisionNodeR = $sxe->nodes->Node[$i];
                    $nodeElementNameR = "right_image";
                    
                    /**************************/
                    $existRightImage = count($decisionNode->right_image);
                    if($existRightImage > 0){
                        unset($decisionNode->right_image);
                    }
                    /**************************/ 
                    
                    foreach($_FILES["$rightChildButtonId"] as $key)
                    {                    
                    
                        $nodeRightImgName = "node".$xml->nodes->Node[$i]->rightChildID.$rightImagecount . ".png";

                        if(!empty($_FILES["$rightChildButtonId"]["tmp_name"][$rightImagecount]) )
                        {
                            //echo "2 " . $rightImagecount . $nodeRightImgName . $rightChildButtonId. "<br>";

                            $splitName = explode(".", $_FILES["$rightChildButtonId"]["name"][$rightImagecount]); // Split file name into an array using the dot
                            $imgFileExt = end($splitName); // Now target the last array element to get the file extensio                         
                            if (strtolower($imgFileExt) != "png") {
                               //echo " image: ". $rightChildButtonId ." ". $nodeRightImgName . " " . $imgFileExt;
                               imageConversion($rightChildButtonId,$nodeRightImgName,$imgFileExt, $rightImagecount);
                               $decisionNodeR->addChild("right_image", $nodeRightImgName); 
                            }
                            else{
                                 move_uploaded_file($_FILES["$rightChildButtonId"]["tmp_name"][$rightImagecount],$uploaddir.$nodeRightImgName);
                                 $decisionNodeR->addChild("right_image", $nodeRightImgName); 
                            }
                        }
                       /* else {
                            //echo "No right child image <br>";
                         $decisionNodeR->addChild("right_image"); 
                        }*/
                        $rightImagecount++;
                    }
                        
                }//end of if
            }//end of for
            
                // FOR PROPER FORMATTING XML
                // Create a new DOMDocument object
                $dom = new DOMDocument('1.0');
                // add spaces, new lines and make the XML more readable format        
                $dom->preserveWhiteSpace = false;
                $dom->formatOutput = true;
                //Load XML document from a string
                $dom->loadXML($sxe->asXML());
                //Save XML to file 
                $dom->save($inputFile);

                //Function to conver .jpg, .gif images to .png format
                function imageConversion($imgName,$newImage,$imgFileExt,$imagecount){
                    $imgFileTmpLoc = $_FILES["$imgName"]["tmp_name"][$imagecount]; // File in the PHP tmp folder
                    $new_png = $_POST["output"].$newImage;
                    $ext = strtolower($imgFileExt);
                    $new_img = "";
                    if ($ext == "gif"){ 
                        $new_img = imagecreatefromgif($imgFileTmpLoc);
                    } 
                    else if($ext =="jpg"){ 
                        $new_img = imagecreatefromjpeg($imgFileTmpLoc);
                    }
                    imagepng($new_img, $new_png);
                    //$organismNode->addChild("$elementName", "$newImage");
                    imagedestroy($imgFileTmpLoc);
                    
                }

        ?>
        <?php include("includes/header.php"); ?>
            <div id="page-wrap2">
                <div id="main-content">

                    <div id="left-col">
                        <?php include("includes/menuAddcharacteristics.php"); ?>
                    </div><!-- end of left-col -->

                <div id = "right-col">
                    <h3>Step 4: Enter characteristics of organisms</h3>
                    <form id="characteristics" action="AddGlossaryTerms.php" method="post">
                        <fieldset id="characteristicsField">
                            <p class="instruction">Please enter characteristics information for each organism. Required fields are indicated by <font color="red" font-weight="bold">*</font>.</p>
                            <?php
                                $uploaddir= $_POST["output"];
                                $inputFile = $uploaddir."keyconversion.xml";
                                $xml = simplexml_load_file($inputFile);
                                $Orgcount = count($xml->organisms->organism);
                                //echo "Organism count = ".$Orgcount."<br />";
                                for($i = 0; $i < $Orgcount; $i++){
                                    echo "<fieldset id='orgchar'>";
                                    $orgIDno = $xml->organisms->organism[$i]->org_id;
                                    echo "<legend><h4 name=\"$orgIDno\">".$xml->organisms->organism[$i]->org_id.".&nbsp".$xml->organisms->organism[$i]->common_name."</h4></legend><br />"; 
                                    $orgID = "Org".$xml->organisms->organism[$i]->org_id;
                                    $orgFamilyName = $orgID."Family";
                                    //echo $orgGenusName."<br/>";
                                    echo "<div id='req' class='characteristicLeftTitle'><label class='c' id='required'>Family:</label> <input type='text' name=\"$orgFamilyName\" required=\"Please Enter Family name\"/></div><br /><br />";
                                    $orgGenusName = $orgID."Genus";
                                    //echo $orgGenusName."<br/>";
                                    echo "<div id='req' class='characteristicLeftTitle'><label class='c' id='required'>Genus:</label><input type='text' name=\"$orgGenusName\" required=\"Please Enter Genus name\"/></div>";
                                    $orgSpeciesName = $orgID."Species";
                                    echo "<div id='req' class='characteristicRightTitle'><label class='c'>epithet:</label><input type='text' name=\"$orgSpeciesName\"/></div><br /><br />";
                                    $orgLeavesName = $orgID."Leaves";
                                    echo "<div class='characteristicLeftTitle'><label class='c'>Leaves:</label> <input type='text' name=\"$orgLeavesName\" /></div>";
                                    $orgInflorescenceName = $orgID."Inflorescence";
                                    echo "<div class='characteristicRightTitle'><label class='c'>Inflorescence:</label> <input type='text' name=\"$orgInflorescenceName\" /></div><br /><br />";
                                    $orgFlowerName = $orgID."Flower";
                                    echo "<div class='characteristicLeftTitle'><label class='c'>Flower:</label> <input type='text' name=\"$orgFlowerName\" /></div>";
                                    $orgFruitName = $orgID."Fruit";
                                    echo "<div class='characteristicRightTitle'><label class='c'>Fruit:</label> <input type='text' name=\"$orgFruitName\" /></div><br /><br />";
                                    $orgEcologyName = $orgID."Ecology";
                                    echo "<div class='characteristicLeftTitle'><label class='c'>Ecology:</label> <input type='text' name=\"$orgEcologyName\" /></div>";
                                    $orgSeedsName = $orgID."Seeds";
                                    echo "<div class='characteristicRightTitle'><label class='c'>Seeds:</label> <input type='text' name=\"$orgSeedsName\" /></div><br /><br />";
                                    $orgElevationName = $orgID."Elevation";
                                    echo "<div class='characteristicLeftTitle'><label class='c'>Elevation:</label> <input type='text' name=\"$orgElevationName\" /></div>";
                                    $orgBioregional_DistributionName = $orgID."Bioregional_Distribution";
                                    echo "<div class='characteristicRightTitle'><label class='c'>Bioregional_Distribution:</label> <input type='text' name=\"$orgBioregional_DistributionName\" /></div><br /><br />";
                                    $orgTaxon_idName = $orgID."Taxon_id";
                                    echo "<div class='characteristicLeftTitle'><label class='c'>Taxon_id:</label> <input type='text' name=\"$orgTaxon_idName\" /></div>";
                                    $orgJepson_urlName = $orgID."Jepson_url";
                                    echo "<div class='characteristicRightTitle'><label class='c'>Jepson_url:</label> <input type='text' name=\"$orgJepson_urlName\" /></div><br /><br />";
                                
                                    echo "</fieldset>";                                    
                                }
                            ?>
 
                          <div style="text-align:center;">
                           <input type="hidden" name="output" value=<?php echo $uploaddir ?> /> <br/><br/>   
                           <input type="submit" class="next" value="Next"/> <br /><br />
                          </div>
                            
                            </fieldset>
                         </form>
                    </div><!-- end of right-col -->

                <div class="clear"></div> <!-- all the content inside main-content div element is floated, need to clear float...
                                              because height of main-content does not know how tall it would be -->

            </div><!-- end of main-content -->        
        </div>  <!-- End of page-wrap -->  
                             
    <?php include("includes/footer.php"); ?>
</body>
</html> 
